<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()">
      <el-form-item label="日期和时间范围：">
        <el-select
          style="width:150px;"
          @change="dateChanged"
          v-model="searchData.currentDate"
          placeholder="请选择"
        >
          <el-option v-for="item in dateSelect" :key="item" :label="item" :value="item"></el-option>
        </el-select>
        <template v-if="showDatePicker">
          <el-date-picker
            style="width:220px;"
            v-model="searchData.startDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="开始时间"
          ></el-date-picker>~
          <el-date-picker
            style="width:220px;"
            v-model="searchData.endDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="结束时间"
          ></el-date-picker>
        </template>
        <el-button @click="search()">查询</el-button>
       <el-button type='primary' @click="download()">下载</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" style="width: 100%;">
      <el-table-column prop="statTime" header-align="center" align="center" label="日期"></el-table-column>
      <el-table-column prop="memberCount" header-align="center" align="center" label="新增会员数"></el-table-column>
      <el-table-column prop="managerCount" header-align="center" align="center" label="新增经理数"></el-table-column>
      <el-table-column prop="directorCount" header-align="center" align="center" label="新增总监数"></el-table-column>
      <el-table-column prop="tatalMemberCount" header-align="center" align="center" label="累计会员数"></el-table-column>
      <el-table-column prop="totalManagerCount" header-align="center" align="center" label="累计经理数"></el-table-column>
      <el-table-column prop="totalDirectorCount" header-align="center" align="center" label="累计总监数"></el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataForm: {
        key: "",
        id: "",
        userId: "",
        nickname: "",
        phone: ""
      },
      searchData: {
        currentDate: "昨日",
        startDate: "",
        endDate: ""
      },
      showDatePicker: false,
      dataList: [],
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dateSelect: [
        "昨日",
        "本周",
        "上周",
        '本月',
        "最近30天",
        "上月",
        "自定义"
      ]
    };
  },
  mounted() {
    let obj = {
      preDay: 1,
      day: 0
    };
    let timeDate = this.getDateData(obj);
    this.searchData.startDate = timeDate.startDate;
    this.searchData.endDate = timeDate.endDate;
  },
  activated() {
    this.getDataList();
  },
  methods: {
    //时间select change事件
    dateChanged(val) {
      let obj = {};
      if (val === "昨日") {
        obj.preDay = 1;
        obj.day = 0;
      } else if (val === "本周") {
        let num = new Date().getDay();
        if (num === 0) {
          obj.preDay = 6;
          obj.day = 6;
        } else {
          obj.preDay = num-1;
          obj.day = 6;
        }
      } else if (val === "上周") {
        let num = new Date().getDay() === 0 ? 7 : new Date().getDay();
        obj.preDay = num + 6;
        obj.day = 6;
      } else if (val === "本月") {
        let num = new Date().getDate();
        obj.preDay = num - 1;
        obj.day = num - 1;
      } else if (val === "最近30天") {
        obj.preDay = 29;
        obj.day = 29;
      } else if (val === "上月") {
        let date = new Date();
        let month = date.getMonth() - 1;
        date.setMonth(month + 1);
        date.setDate(0);
        let monthNum = date.getDate();
        let num = monthNum + new Date().getDate();
        obj.preDay = num-1;
        obj.day = monthNum-1;
      }

      if (val === "自定义") {
        this.searchData.startDate = "";
        this.searchData.endDate = "";
        this.showDatePicker = true;
        return;
      } else {
        let timeDate = this.getDateData(obj);
        console.log("timeDate====>", timeDate);
        this.searchData.startDate = timeDate.startDate;
        console.log("this.searchData.endDate====>", timeDate.endDate);
        this.searchData.endDate = timeDate.endDate;
        // if (val === "本周" || val === "最近30天") {
        //   this.searchData.endDate = new Date();
        // } else {
        //   this.searchData.endDate = timeDate.endDate;
        // }
      }
      this.showDatePicker = false;
    },
    search() {
      this.pageIndex = 1
      this.getDataList()
    },
    getDateData(data) {
      let obj = {};
      obj.startDate = "";
      obj.endDate = "";
      if (data && data.preDay + "") {
        let time = Date.now();
        let startDate = getDateText(time - data.preDay * 24 * 3600 * 1000);
        let endDate = getDateText(
          time - data.preDay * 24 * 3600 * 1000 + data.day * 24 * 3600 * 1000
        );
        obj.startDate = startDate;
        obj.endDate = endDate;
      }

      function getDateText(timeMinutes) {
        let date = new Date(timeMinutes);
        let year = date.getFullYear();
        let month =
          date.getMonth() > 8
            ? date.getMonth() + 1
            : "0" + (date.getMonth() + 1);
        let dayText =
          date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
        console.log(dayText)
        return year + "-" + month + "-" + dayText;
      }
      return obj;
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      let obj = {
        page: this.pageIndex,
        limit: this.pageSize,
        key: this.dataForm.key
      };
      obj.startDate = this.searchData.startDate;
      obj.endDate = this.searchData.endDate;
      this.$http({
        url: this.$http.adornUrl("/saleStatistic/usergradestatistic/list"),
        method: "get",
        params: this.$http.adornParams(obj)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    download() {
      let obj = {
        page: this.pageIndex,
        limit: this.pageSize
      };
      obj.startDate = this.searchData.startDate;
      obj.endDate = this.searchData.endDate;
      this.$http({
        url: this.$http.adornUrl("/saleStatistic/usergradestatistic/download"),
        method: "get",
        params: this.$http.adornParams(obj),
        headers: {
          'Content-Type': 'application/json; application/octet-stream'
        },
        responseType: 'arraybuffer'
      }).then(({ data }) => {
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        downloadElement.download = '用户统计.xls'
        document.body.appendChild(downloadElement)
        downloadElement.click()
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
      })
    }
  }
};
</script>
